package net.hhk.twitter;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import java.util.ArrayList;
import java.util.List;

import net.hhk.controller.TweetAdapter;
import net.hhk.controller.TweetManager;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import net.hhk.data.Tweet;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class MyTweetActivity extends ListActivity {

	private TweetAdapter mAdapter;
	// private SimpleAdapter mAdapter;
	private View mLoadMoreFooter;

	private boolean mLoading;

	private static final int MSG_APPEND_MORE_ITEMS = 0;

	private static final int NUMBER_OF_ITEMS_REQUESTED = 6;
	private int currentPage = 1;
	private TweetManager mgr;
	private int id;
	MySharePreferences sharePre;
	public LayoutInflater inflater;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_tweet_layout);
		Bundle b = getIntent().getExtras();
		sharePre = (MySharePreferences) getApplicationContext();

		id = b.getInt("id");
		inflater = LayoutInflater.from(this);
		mLoadMoreFooter = inflater.inflate(R.layout.profile, null);

		TextView my_tweet_title = (TextView) findViewById(R.id.my_tweet_title);
		my_tweet_title.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(),
						MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(i);
				finish();
			}
		});

		LinearLayout write_tweet = (LinearLayout) findViewById(R.id.home_write_tweet);
		write_tweet.setOnClickListener(clickWriteTweet);

		Button btn = (Button) findViewById(R.id.btn_tweet);
		btn.setOnClickListener(clickWriteTweet);

		LinearLayout searchLayout = (LinearLayout) findViewById(R.id.btnSearch_layout);
		searchLayout.setOnClickListener(clickSearch);
		Button btnSearch = (Button) findViewById(R.id.btn_search);
		btnSearch.setOnClickListener(clickSearch);

		getListView().addFooterView(mLoadMoreFooter);
		// getListView().addHeaderView(mLoadMoreFooter);

		getListView().setOnScrollListener(mScrollListener);

		mLoading = false;
		mgr = new TweetManager(getApplicationContext());
		loadData();
		ListView list = getListView();
	}

	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadData();
		currentPage = 1;
		if (getListView().getFooterViewsCount() == 0) {
			getListView().addFooterView(mLoadMoreFooter);
		}
		getListView().setOnScrollListener(mScrollListener);
		mLoading = false;
	}

	private OnClickListener clickWriteTweet = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(),
					WriteTweetActivity.class);
			Bundle b = new Bundle();

			b.putInt("isReply", 0);
			i.putExtras(b);
			startActivity(i);

		}
	};

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		// List<Tweet> tweets = mgr.getTweets();
		Tweet tweet = (Tweet) l.getItemAtPosition(position);
		int tweetid = tweet.getTweetId();
		String tweetUser = tweet.getNameRweet();
		Boolean isfavor = tweet.getIsMyFavorite();
		Boolean isretweet = tweet.getIsMyRetweet();
		sharePre.setExitString("currentVisitUsername", tweet.getUserName());
		Intent i = new Intent(getApplicationContext(), ViewTweetActivity.class);
		Bundle b = new Bundle();
		b.putInt("id", tweetid);
		b.putString("retweetUser", tweetUser);
		b.putBoolean("isfavorite", isfavor);
		b.putBoolean("isretweet", isretweet);

		// Your id
		i.putExtras(b); // Put your id to your next Inten
		startActivity(i);
	}

	private void loadData() {
		AsyncTask<String, Void, List<Tweet>> asyncTask = new AsyncTask<String, Void, List<Tweet>>() {
			private ProgressDialog progressDialog = new ProgressDialog(
					MyTweetActivity.this);

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				progressDialog.setTitle("Loading Tweets");
				if (!progressDialog.isShowing()) {
					progressDialog.show();
				}
			}

			@Override
			protected List<Tweet> doInBackground(String... params) {
				// Following actions will be done in background
				if (id > 0) {
					return mgr.getSocialFeed(Constant.GET_USER_TWEET, id, 1, 6);
				} else
					return mgr.getSocialFeed(Constant.GET_MY_TWEET, id, 1, 6);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<Tweet> result) {
				super.onPostExecute(result);
				if (progressDialog.isShowing()) {
					progressDialog.hide();
				}
				// TweetAdapter listAdapter = new TweetAdapter(
				// getApplicationContext(), result);
				mAdapter = new TweetAdapter(MyTweetActivity.this, result);
				setListAdapter(mAdapter);

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void loadMoreItems() {
		mLoading = true;

		new Thread() {
			public void run() {
				try {
					// in this example, we just simply wait for 2 seconds
					Thread.sleep(2000);
					Message msg = mMainhandler.obtainMessage(
							MSG_APPEND_MORE_ITEMS, generateList());
					mMainhandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private Handler mMainhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPEND_MORE_ITEMS:
				ArrayList newData = (ArrayList) msg.obj;
				if (mAdapter == null) {
					mAdapter = new TweetAdapter(MyTweetActivity.this, newData);
					setListAdapter(mAdapter);
				} else {

					mAdapter.appendItems(newData);
				}

				// if the list we get from server is smaller than 15 (in this
				// example)
				// then that means there's nothing more to get, remove the
				// loading item now
				if (newData.size() < NUMBER_OF_ITEMS_REQUESTED) {
					getListView().removeFooterView(mLoadMoreFooter);
				}
				mLoading = false;
				break;

			}

		}
	};

	private ArrayList generateList() {
		currentPage++;
		if (id > 0) {
			return (ArrayList<Tweet>) mgr.getSocialFeed(
					Constant.GET_USER_TWEET, id, currentPage,
					NUMBER_OF_ITEMS_REQUESTED);
		} else
			return (ArrayList<Tweet>) mgr.getSocialFeed(Constant.GET_MY_TWEET,
					id, currentPage, NUMBER_OF_ITEMS_REQUESTED);
	}

	private void checkLoadMore() {
		if (mLoading)
			return;

		/*
		 * if the loading footer is still there, then we will load more items
		 */
		if (getListView().getFooterViewsCount() != 0) {
			loadMoreItems();
		}
	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// We have nothing to do with this right now
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// minus 1 here because the total list item count include the
			// loading footer
			if (view.getLastVisiblePosition() >= 0) {
				if (view.getLastVisiblePosition() >= (totalItemCount - 1)) {

					checkLoadMore();
				}
			}
		}
	};

}